package com.gitee.zycra.file.pool;

import com.gitee.zycra.file.config.ConnectionConfig;
import com.jcraft.jsch.ChannelSftp;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

import java.time.Duration;

/**
 * Container for pooled object of {@link ChannelSftp}.
 *
 * @author zycra
 * @since 1.0.0
 */
public final class SessionPool {

    /**
     * Max wait time for create connection.
     *
     * @since 1.0.0
     */
    private static final long MAX_WAIT_MILLIS = 60000L;

    /**
     * Time between eviction runs.
     *
     * @since 1.0.0
     */
    private static final long TIME_BETWEEN_EVICTION_RUNS_MILLIS = 300000L;
    private static final GenericKeyedObjectPool<ConnectionConfig, ChannelSftp> SFTP_SESSION_POOL;

    static {
        GenericKeyedObjectPoolConfig<ChannelSftp> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxWait(Duration.ofMillis(MAX_WAIT_MILLIS));
        config.setTimeBetweenEvictionRuns(Duration.ofMillis(TIME_BETWEEN_EVICTION_RUNS_MILLIS));
        config.setTestOnBorrow(true);
        SFTP_SESSION_POOL = new GenericKeyedObjectPool<>(new SessionFactory(), config);
    }

    private SessionPool() {
    }

    public static GenericKeyedObjectPool<ConnectionConfig, ChannelSftp> getPool() {
        return SFTP_SESSION_POOL;
    }
}
